package com.sky.controller.user;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.result.Result;
import com.sky.service.AddressbookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user/addressBook")
@Api(tags = "C端.地址接口")
@Slf4j
public class AddressbookController {
    @Autowired   AddressbookService addressbookService;
//新增地址
    @PostMapping
    @ApiOperation("新增地址")
public Result add(@RequestBody AddressBook addressBook){
        log.info("新增地址");
    addressbookService.add(addressBook);
          return Result.success();
}
//查询用户所有地址
    @GetMapping("/list")
    @ApiOperation("查询用户地址")
    public Result<List<AddressBook>>select(){
        log.info("查询用户地址");
List<AddressBook> list=addressbookService.select();
        return Result.success(list);
    }
//查询默认地址
    @GetMapping("/default")
    @ApiOperation("查询默认地址")
    public Result<AddressBook> selectdefault(){
        //addressbookService.selectdefault(addressBook);
        //SQL:select * from address_book where user_id = ? and is_default = 1
        log.info("查询默认地址");
        AddressBook addressBook = new AddressBook();
        addressBook.setIsDefault(1);
        //获取用户id
        addressBook.setUserId(BaseContext.getCurrentId());
        List<AddressBook> list = addressbookService.list(addressBook);

        if (list != null && list.size() == 1) {
            return Result.success(list.get(0));
        }

        return Result.error("没有查询到默认地址");
    }
//修改地址
    @PutMapping
    @ApiOperation("根据id修改地址")
    public Result update(@RequestBody AddressBook addressBook ){
        log.info("修改地址：{}", addressBook);
   addressbookService.update(addressBook);
        return Result.success();
    }
    //根据id查询地址
    @GetMapping("/{id}")
    @ApiOperation("根据id查询地址")
            public Result<AddressBook>  seleteById(@PathVariable Long id) {
        log.info("根据id查询地址");
       AddressBook addressBook=addressbookService.selectById(id);
return Result.success(addressBook);
    }
    //根据id删除地址
@DeleteMapping()
@ApiOperation("根据id删除地址")
    public  Result deleteID(Long id){
    log.info("根据id删除地址");
    addressbookService.deleteID(id);

    return Result.success();
}
//设置默认地址
 @PutMapping("/default")
    @ApiOperation("设置默认地址")
    public Result setting(@RequestBody AddressBook addressBook){
        log.info("设置默认地址");
        addressbookService.setting(addressBook);

        return Result.success();
 }



}
